import os
from flask import Blueprint, request, current_app, jsonify
from app.utils.response_util import ResponseUtil
from flask_login import login_required, current_user
import traceback
import logging
from werkzeug.utils import secure_filename
from app.services.upload_service import UploadService
from app.utils.minio_util import MinioUtil

bp = Blueprint('upload', __name__, url_prefix='/api')
logger = logging.getLogger(__name__)

@bp.route('/upload_image', methods=['POST'])
@login_required
def upload_image():
    """
    Handle image upload with enhanced validation and error handling
    """
    try:
        logger.info("Starting image upload process")
        logger.info(f"Files in request: {request.files}")
        logger.info(f"Form data: {request.form}")
        
        # FilePond sends the file with the field name specified in the 'name' option
        file = None
        if 'file' in request.files:
            file = request.files['file']
        elif 'images' in request.files:
            file = request.files['images']
        
        if not file:
            logger.warning("No file found in request")
            logger.warning(f"Available files: {list(request.files.keys())}")
            return ResponseUtil.error("No file provided", 400)

        # Check if file was selected
        if file.filename == '':
            logger.warning("No file selected")
            return ResponseUtil.error("No file selected", 400)

        # Log file details
        logger.info(f"Received file: {file.filename}")
        logger.info(f"Content Type: {file.content_type}")
        
        # Initialize services
        upload_service = UploadService()
        
        try:
            # Upload file and get URL
            url = upload_service.upload_image(file)
            if not url:
                logger.error("File upload failed - no URL returned")
                return ResponseUtil.error("File upload failed", 500)

            logger.info(f"File upload successful: {url}")
            return ResponseUtil.success({
                "url": url,
                "filename": file.filename
            })

        except ValueError as ve:
            # Validation errors
            logger.warning(f"Validation error during upload: {str(ve)}")
            return ResponseUtil.error(str(ve), 400)
            
        except Exception as e:
            # Unexpected errors during upload
            logger.error(f"Error during file upload: {str(e)}")
            logger.error(traceback.format_exc())
            return ResponseUtil.error("An error occurred during file upload", 500)

    except Exception as e:
        # Catch-all for unexpected errors
        logger.error(f"Unexpected error in upload route: {str(e)}")
        logger.error(traceback.format_exc())
        return ResponseUtil.error("An unexpected error occurred", 500)